<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Libraries\vendor\SphinxClient;
use Illuminate\Support\Facades\DB;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 不自动返回的validate
     * @see Illuminate\Contracts\Validation
     * @throws json
     */
    protected function manual_validate($data, $rules){
        if(!is_array($data)){ $data = $data->only(array_keys($rules)); }

        $validator = Validator::make($data, $rules);
        if($validator->fails()){
            die(json_encode(msg($validator->messages()->all())));
        }
    }
    
    /**
     * 通用排序
     * @author liuchang
     */
    protected function _order(&$builder, $defaults=[]){
        $order = request()->input('_order');
        if($order){
            $order = explode('|', $order);
            foreach($order as $k=>$v){
                if(!$v){ continue; }
                $tmp = explode('=', $v);
                $builder = $builder->orderBy($tmp[0], $tmp[1]);

                foreach($defaults as &$default){
                    if($default == $tmp[0]){
                        $default = false;
                    }
                }
            }
        }
        
        foreach($defaults as $k=>$v){ // 默认排序条件（会被覆盖）
            if($v){
                $builder = $builder->orderBy($k, $v);
            }
        }
    }

    /**
     * 通用搜索
     * @author liuchang
     */
    public function _search(&$builder, &$search=[], $filters=[], $join=[],$index='article',&$words=[]){
        $search = request()->input('_search');
        if($search){
            $search = explode('|', urldecode($search));
            foreach($search as $k=>&$v){
                $v = explode('=', $v);
                if(isset($v[0]) && ($v[0]=='left' || $v[0]=='right')){
                    $tmp[$v[0]] = $v[1];
                    continue;
                }
                if(isset($v[1]) && $v[1] != ''){
                    $filters = is_string($filters) ? [$filters] : $filters;
                    foreach($filters as $filter){ // 过滤需要单独处理的参数
                        if($filter == $v[0]){
                            $tmp[$v[0]] = $v[1];
                            continue 2;
                        }
                    }

                    if(strstr($v[0], '.')){ // 需要连表查询的参数
                        $t = explode('.', $v[0]);
                        if(isset($join[$t[0]])){
                            $builder = $builder->leftJoin($t[0], $join[$t[0]][0], '=', $join[$t[0]][1]);
                        }
                    }

                    // 根据不同类型的字段选择查询方法
                    if($v[0]=='invitation_code'){
                        $info = DB::table('user_tree')->where('invitation_code',$v[1])->first(['uid']);
                        $builder = $builder->where('uid',$info->uid);
                    }elseif($v[0]=='phone'){

                        if(strlen($v[1])==11){
                            $info = DB::table('user_tree')->where('phone',$v[1])->first(['uid']);
                            $builder = $builder->where('uid',$info->uid); 
                        }else{
                            if(stripos($v[1], '*')){
                                $ex = explode('*',$v[1]);
                                $builder = $builder->where('phone','like',$ex[0].'%'.$ex[1]); 
                            }else{
                                $builder = $builder->where('phone','like','%'.$v[1].'%'); 
                            }
                        }
                        
                    }
                    elseif($v[0]=='refund'){

                    }elseif($v[0]=='add_time'){
                        $start = strtotime($v[1]);
                        $end = strtotime($v[1]." 23:59:59");
                        $builder = $builder->whereBetween('add_time',[$start,$end]);
                    }
                    elseif($this->is_key($v[0])){
                        if($builder->from=='article' || $builder->from=='video'){
                            $sphinxmatch = sphinxClient::getClient()->Query($v[1], $index);
                            $words = $sphinxmatch['words']??[];
                            if ($sphinxmatch['total'] > 0) {
                                $ids = sphinxClient::getClient()->allid($sphinxmatch['matches']);
                                $builder=$builder->whereIn('id',$ids);
                            }
                        }else{
                          $v[1] =trim($v[1]);
                            $builder = $builder->where('title', 'like', '%'.$v[1].'%');  
                        }
                    }elseif($this->is_time_field($v[0])){ // 日期时间查询字段
                        $builder = $builder->whereDate($v[0], $v[1]);
                    }elseif($this->is_equal_field($v[0])){ // 等号查询字段
                        $builder = $builder->where($v[0], '=', $v[1]);
                    }else{
                        $builder = $builder->where($v[0], 'like', '%'.$v[1].'%');
                    }
                }
                $tmp[$v[0]] = $v[1];
                unset($v);
            }
            $search = $tmp;
        }
    }

    public function getSearchParams()
    {
        $search = request()->input('_search');
        $tmp = [];
        if($search)
        {
            $search = explode('|', urldecode($search));
            foreach($search as $k=>&$v){
                $v = explode('=', $v);
                if(isset($v[0])){
                    $tmp[$v[0]] = $v[1];
                }
            }
            return $tmp;
        }
        return [];
    }

    /**
     * 判断是否为用 = 号查询的字段
     * @author liuchang
     * @param String field
     * @return bool
     */
    public function is_equal_field($field = ''){
        $list = [
            '/.*id/i',
            '/.*status/i',
            '/.*type/i',
        ];

        foreach($list as $pattern){
            if(preg_match($pattern, $field) > 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为时间字段
     * @author liuchang
     * @param String field
     * @return bool
     */
    public function is_time_field($field = ''){
        $list = [
            '/.*time/i',
            '/.*date/i',
            '/.*datetime/i',
            '/.*timedate/i',
            '/.*add_time/i',
        ];

        foreach($list as $pattern){
            if(preg_match($pattern, $field) > 0){
                return true;
            }
        }
        return false;
    }

    public function is_key($field){
        if($field=='key'){
            return true;
        }
        return false;
    }
}
